package minijvm.cmd;

import minijvm.clz.ClassFile;
import minijvm.constant.ClassInfo;
import minijvm.constant.FieldRefInfo;
import minijvm.constant.NameAndTypeInfo;
import minijvm.engine.ExecutionResult;
import minijvm.engine.JavaObject;
import minijvm.engine.StackFrame;

/**
 * @author ChangLiang
 * @date 2020/4/26
 */
public class PutFieldCmd extends TwoOperandCmd {
    public PutFieldCmd(ClassFile clzFile, String opCode) {
        super(clzFile, opCode);
    }

    @Override
    public void execute(StackFrame frame, ExecutionResult result) {
        FieldRefInfo fieldRefInfo = (FieldRefInfo) this.getConstantInfo(getIndex());
        ClassInfo classInfo = (ClassInfo) this.getConstantInfo(fieldRefInfo.getClassInfoIndex());
        NameAndTypeInfo nameAndTypeInfo = (NameAndTypeInfo) getConstantInfo(fieldRefInfo.getNameAndTypeIndex());
        // e.g. name or age
        String fieldName = nameAndTypeInfo.getName();
        // e.g. Ljava/lang/String or I  这里没有进行类型检查
        String fieldType = nameAndTypeInfo.getTypeInfo();

        // "andy" or 29
        JavaObject fieldValue = frame.getOperandStack().pop();
        // this
        JavaObject objectRef = frame.getOperandStack().pop();
        objectRef.setFieldValue(fieldName,fieldValue);
    }
}
